package com.haiyou.mini.programs.config;


import com.haiyou.common.exception.BusinessException;
import com.haiyou.common.util.StringUtils;
import com.haiyou.mini.programs.wxpay.IWxPayDomain;
import com.haiyou.mini.programs.wxpay.WxPayConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 微信配置类
 *
 * @author huangzl
 */
@Slf4j
@Data
public class WxMiniConfig extends WxPayConfig {

    private String appId;
    private String secret;
    private String payKey;
    private String mchId;
    private String page;
    private String notifyUrl;
    private String certFile;
    private byte[] certData;
    /**
     * 证书序列号
     */
    private String serialNo;
    /**
     * 商户私钥路径
     */
    private String rsaPrivateKeyFile;
    /**
     * 商户公钥路径
     */
    private String rsaPublicKeyFile;

    @Override
    public String getAppID() {
        return appId;
    }

    @Override
    public String getMchID() {
        return mchId;
    }

    @Override
    public String getKey() {
        return payKey;
    }

    /**
     * 获取退款、撤销时的商户证书
     */
    public void initCertFile() throws Exception {
        if (StringUtils.isEmpty(certFile)) {
            throw new BusinessException("请配置商户证书");
        }
        String certPath = System.getProperty("user.dir") + certFile;
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    public String getRsaPrivateKeyFile() {
        return System.getProperty("user.dir") + rsaPrivateKeyFile;
    }

    public String getRsaPublicKeyFile() {
        return System.getProperty("user.dir") + rsaPublicKeyFile;
    }

    @Override
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    @Override
    public IWxPayDomain getWXPayDomain() {
        return new IWxPayDomain() {

            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {
            }

            @Override
            public DomainInfo getDomain(WxPayConfig config) {
                return new DomainInfo("api.mch.weixin.qq.com", false);
            }
        };
    }
}
